package com.cinema;

import java.io.IOException;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cinema.data.PMF;
import com.cinema.data.User;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class Signin extends HttpServlet{

	/**
	 * 
	 */
	public Signin(){
		super();
	}
	private static final long serialVersionUID = 4010782057746594985L;
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		doPost(req, resp);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		Boolean isAuth = false;
		
		/*Key userKey = KeyFactory.createKey("User", username);
		Entity user = null;
		User usr = new User();
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		try{
			user = datastore.get(userKey);
			String temp = (String) user.getProperty("password");
			if (temp.equals(password)){
				isAuth = true;
				usr.setUsername(username);
				usr.setFullname((String) user.getProperty("fullname"));
				usr.setEmail((String) user.getProperty("email"));
			}else
				isAuth = false;
		}catch(EntityNotFoundException e){
			isAuth = false;
		}*/
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Key k = KeyFactory.createKey(User.class.getSimpleName(), username);
		User usr = null;
		try{
			usr = pm.getObjectById(User.class, k);
			if(usr.getPassword().equals(password))
				isAuth = true;
			else
				isAuth = false;
		}catch(JDOObjectNotFoundException e){
			isAuth = false;
		}finally{
			pm.close();
		}
		if(isAuth){
			request.setAttribute("user", usr);
			String url = "/UserInfo.jsp";
			RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher(url);
			try {
				dispatcher.forward(request, response);
			} catch (ServletException e) {
				e.printStackTrace();
			}
		}else{
			response.sendRedirect("signin.html");
		}
	}
}